<template>
  <div class="form-container" v-loading="loading">
    <div class="top">
      <el-form size="mini" ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item prop="cate_ids" label="物资类型">
          <el-cascader v-model="form.cate_ids" :options="options" :props="props" clearable></el-cascader>
        </el-form-item>
        <el-form-item prop="min_amount" label="期望的回收量">
          <el-radio-group v-model="form.amount">
            <el-radio :label="0">不限制</el-radio>
            <el-radio :label="1">指定范围</el-radio>
          </el-radio-group>
          <div class="line">
            <el-input v-model="form.min_amount" placeholder="最小回收量" type="number" />至
            <el-input v-model="form.max_amount" placeholder="最大回收量" type="number" />
          </div>
        </el-form-item>
        <el-form-item prop="min_money" label="期望的回收金额">
          <el-radio-group v-model="form.money">
            <el-radio :label="0">不限制</el-radio>
            <el-radio :label="1">指定范围</el-radio>
          </el-radio-group>
          <div class="line">
            <el-input v-model="form.min_money" placeholder="最小回收金额" type="number" />至
            <el-input v-model="form.max_money" placeholder="最大回收金额" type="number" />
          </div>
        </el-form-item>
        <el-form-item prop="key_words" label="特定要求">
          <div class="keyword-list" style="margin-bottom: 5px">
            <el-tag size="small" v-for="(item, index) in keywordList" disable-transitions @close="handleDeleteKeyword(index)" :key="item + index" closable type="info" style="margin-right: 5px">
              {{ item }}
            </el-tag>
          </div>
          <el-input class="long" maxlength="20" v-model="keyword" placeholder="例如：名称、品牌、参数等（不超过20个字）"></el-input>
          <el-tag size="small" style="cursor: pointer" @click="handleAddKeyword" type="danger">添加 +</el-tag>
        </el-form-item>
        <el-form-item prop="alarm_method" label="提醒方式">
          <el-checkbox-group v-model="form.alarm_method">
            <el-checkbox :label="1">APP推送</el-checkbox>
            <el-checkbox :label="2">微信服务通知</el-checkbox>
            <el-checkbox :label="3">短信</el-checkbox>
            <el-checkbox :label="4">AI电话</el-checkbox>
            <el-checkbox :label="5">人工联系</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </div>
    <div class="bottom">
      <el-divider></el-divider>
      <div class="line">
        <el-button size="mini" @click="onDelete" v-if="id">删除</el-button>
        <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { apiSignCateSelect, apiVipCateDel, apiVipCateSet, apiSignCateDetail } from '@/api/assetsDisposal'

export default {
  props: {
    cateList: Array,
    id: String,
    userId: String,
  },
  data() {
    var validaAmount = (rule, value, callback) => {
      if (this.form.amount === 1) {
        if (!this.form.min_amount) {
          callback(new Error('请填写最小值'))
        } else if (!this.form.max_amount) {
          callback(new Error('请填写最大值'))
        } else if (this.form.min_amount < 0) {
          callback(new Error('最小值不能小于0'))
        } else if (this.form.max_amount < 0) {
          callback(new Error('最大值不能小于0'))
        } else if (!this.form.max_amount) {
          callback(new Error('请填写最大值'))
        } else if (Number(this.form.min_amount) >= Number(this.form.max_amount)) {
          callback(new Error('最大值必须大于最小值'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validaMoney = (rule, value, callback) => {
      if (this.form.money === 1) {
        if (!this.form.min_money) {
          callback(new Error('请填写最小值'))
        } else if (!this.form.max_money) {
          callback(new Error('请填写最大值'))
        } else if (this.form.min_money < 0) {
          callback(new Error('最小值不能小于0'))
        } else if (this.form.max_money < 0) {
          callback(new Error('最大值不能小于0'))
        } else if (!this.form.max_money) {
          callback(new Error('请填写最大值'))
        } else if (Number(this.form.min_money) >= Number(this.form.max_money)) {
          callback(new Error('最大值必须大于最小值'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      keyword: '', // 输入框输入的关键词
      keywordList: [], // 关键词列表
      form: {
        cate_ids: [],
        amount: 0,
        min_amount: '',
        max_amount: '',
        money: 0,
        min_money: '',
        max_money: '',
        key_words: '',
        alarm_method: [1, 2, 3],
      },
      rules: {
        cate_ids: [{ required: true, message: '请选择物资类型', trigger: 'blur' }],
        min_amount: [{ validator: validaAmount, trigger: 'blur' }],
        min_money: [{ validator: validaMoney, trigger: 'blur' }],
      },
      loading: false,
      props: { value: 'num_id', label: 'name' },
      value: [],
      options: [],
    }
  },
  watch: {},
  computed: {},
  mounted() {
    this.value = this.default
    this.getSignCateSelect()
  },
  methods: {
    // 获取类别
    getSignCateSelect() {
      apiSignCateSelect().then((res) => {
        if (res.code === 200) {
          const { data } = res
          data.forEach((item1) => {
            if (item1.children && item1.children.length === 0) {
              delete item1.children
            } else {
              item1.children.forEach((item2) => {
                if (item2.children && item2.children.length === 0) {
                  delete item2.children
                }
              })
            }
          })
          // 已经有的禁用
          this.cateList
            .filter((item) => item.id !== this.id)
            .forEach((item) => {
              const nameList = item.cate_name.split(' ')
              const length = nameList.length
              const name = nameList[length - 1]
              this.setDisable(data, name)
            })
          this.options = data
          this.getDetail()
        }
      })
    },
    setDisable(current, name) {
      if (!current || !name) {
        return
      }
      current.forEach((option) => {
        if (option.name === name) {
          option.disabled = true
        } else {
          this.setDisable(option.children, name)
        }
      })
    },
    // 获取详情
    getDetail() {
      if (this.id) {
        const formData = new FormData()
        formData.set('id', this.id)
        apiSignCateDetail(formData).then((res) => {
          if (res.code === 200) {
            const { data } = res
            // 类别名称转id
            if (data.cate_name.length > 0) {
              const cateItems = []
              const cateNames = data.cate_name.split(' ')

              cateNames.forEach((item, index) => {
                if (index === 0) {
                  const cate1 = this.options.find((option) => option.name === item)
                  if (cate1) {
                    cateItems.push(cate1)
                  } else {
                    return
                  }
                } else {
                  const cate1 = cateItems[index - 1].children.find((option) => option.name === item)
                  if (cate1) {
                    cateItems.push(cate1)
                  } else {
                    return
                  }
                }
              })

              this.form.cate_ids = cateItems.map((item) => item.num_id)
            }
            if (data.min_amount === 0 && data.min_amount === data.max_amount) {
              this.form.amount = 0
            } else {
              this.form.amount = 1
              this.form.min_amount = data.min_amount
              this.form.max_amount = data.max_amount
            }
            if (data.min_money === 0 && data.min_money === data.max_money) {
              this.form.money = 0
            } else {
              this.form.money = 1
              this.form.min_money = data.min_money
              this.form.max_money = data.max_money
            }
            this.form.alarm_method = data.alarm_method.map((item) => parseInt(item))
            if (data.key_words && data.key_words.length > 0) {
              this.keywordList = data.key_words.split(',')
            }
          }
        })
      }
    },
    // 确定
    onSubmit() {
      this.$refs.form.validate((flag) => {
        if (flag) {
          const form = {
            cate_ids: this.form.cate_ids,
            alarm_method: this.form.alarm_method,
          }
          if (this.form.amount === 1) {
            form.min_amount = this.form.min_amount
            form.max_amount = this.form.max_amount
          }
          if (this.form.money === 1) {
            form.min_money = this.form.min_money
            form.max_money = this.form.max_money
          }
          form.user_id = this.userId
          if (this.id) {
            form.id = this.id
          }
          form.key_words = this.keywordList.join(',')
          const formData = new FormData()
          for (let key in form) {
            formData.set(key, form[key])
          }
          apiVipCateSet(formData).then((res) => {
            if (res.code === 200) {
              this.$emit('confirm')
            }
          })
        }
      })
    },
    // 删除
    onDelete() {
      const form = {
        id: this.id,
        send_to_feijiu: 1,
      }
      const formData = new FormData()
      for (let key in form) {
        formData.set(key, form[key])
      }
      apiVipCateDel(formData).then((res) => {
        if (res.code === 200) {
          this.$emit('delete', this.id)
        }
      })
    },
    // 添加关键字
    handleAddKeyword() {
      if (!this.keyword) {
        return
      }
      this.keywordList.push(this.keyword)
      this.keyword = ''
    },
    // 删除关键字
    handleDeleteKeyword(index) {
      this.keywordList.splice(index, 1)
    },
  },
}
</script>
<style lang="scss" scoped>
.form-container {
  padding: 0 24px;
  .top {
    min-height: 300px;
  }
  .bottom {
    .line {
      display: flex;
      justify-content: flex-end;
    }
  }
  .el-cascader {
    width: 100%;
    .el-input {
      width: 100% !important;
      margin: 0 !important;
    }
  }
  .el-input {
    width: 150px !important;
    margin: 0 5px !important;
  }
  .long.el-input {
    width: 83% !important;
    margin: 0 !important;
    margin-right: 20px !important;
  }

  .line {
    display: inline-block;
    margin-left: 10px;
  }
}
</style>

<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}
</style>
